package cn.rayland.library.stm32;


import java.io.File;
import java.io.FileDescriptor;

import libcore.io.ErrnoException;
import libcore.io.Libcore;
import libcore.io.Os;
import libcore.io.OsConstants;

/**
 * Created by zx on 15-8-3.
 */
public class IIC {
    static public String stm32 = "/dev/stm32";
    static private IIC stm32IIC = null;
    static public IIC getInstance(){
        if (stm32IIC == null)
            stm32IIC = new IIC();
        return stm32IIC;
    }

    private IIC() {
        os = Libcore.os;
        try {
            fd = os.open(stm32, OsConstants.O_RDWR, 0);
            os.lseek(fd, 0x2f, OsConstants.SEEK_SET);
        } catch (Exception e) {
            e.printStackTrace();
        }
        catch (Error e){
            e.printStackTrace();
        }
    }

    private Os os;
    private FileDescriptor fd;

    public boolean haveDevice() {
        return new File(stm32).exists();
    }

    public void sendData(byte[] buffer, int offset, int count) {
        if (count > 0) {
            try {
                os.write(fd, buffer, offset, count);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void sendData(int numBytes, byte[] buffer) { sendData(buffer, 0, numBytes); }

    public void sendData(byte[] buffer) {
        sendData(buffer.length, buffer);
    }

    public void readData(int numBytes, byte[] buffer) {
        if (numBytes > 0) {
            try {
                os.read(fd, buffer, 0, numBytes);
            } catch (Exception e) {
//                e.printStackTrace();
            }
        }
    }

    public byte[] readData(int numBytes) {
        byte[] buffer = new byte[numBytes];
        readData(numBytes, buffer);
        return buffer;
    }

    public void onDestroy() {
        try {
            os.close(fd);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
